<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>选择差旅政策</title>
    <link rel="stylesheet" href="../../../css/iconfont/iconfont.css"/>
    <link rel="stylesheet" href="../../../css/font/alifont.css" />
    <link rel="stylesheet" href="../../../css/aui.css" />
    <link rel="stylesheet" href="../../../css/index/train/select_travel_policy.css" />
</head>

<body style="cursor: pointer">
    <div class="aui-card-list">
        <div class="aui-card-list-header">
            <div> <span class="aui-text-danger"> 乘客</span></div>
        </div>
        <div class="aui-card-list-content">
            <ul class="aui-list aui-media-list user_list">

            </ul>
        </div>
        <div class="aui-card-list-header">
            <div> <span class="aui-text-danger">选择差旅政策</span></div>
        </div>
        <div class="aui-card-list-content">
            <ul class="aui-list aui-media-list policy_list">

            </ul>
        </div>
    </div>
    <span class="notice">请确认本订单中的出行人可使用相同的差旅政策，否则需分开预定</span>
    <div class="confirm">
        <p>
            <div class="aui-btn  aui-btn-block" style="background: #3CB0D6;color:#DBF0F7;font-size: 0.8rem;background: #3CB0D6;" onclick="confirm_policy()">确定</div>
        </p>
    </div>
</body>
<script src="../../../script/extend/jquery-3.3.1.min.js"></script>
<script src="../../../script/aui/api.js"></script>
<script src="../../../script/extend/doT.min.js"></script>
<script src="../../../script/aui/aui-toast.js"></script>
<script src="../../../script/config.js"></script>
<script src="../../../script/common.js"></script>
<script>
    let card_submit_type   = parseInt($api.getStorage('card_submit_type'));//完成返回页面标识 0火车票 1机票 2酒店
    let user_id            = $api.getStorage('user_id');//当前登录人id
    let isApply            = parseInt($api.getStorage('isApply'));//是否开启出差申请单,0关闭，1开启
    let policyData,//差旅政策数据
        policy_execute,//选中的差旅政策
        /* 机票参数 */
        plane_msg,//舱位信息
        travel_people,//出行人
        planeInfo,//航班信息
        /* 车票参数 */
        train_type,//座位类型
        seat_name,//座位名
        /* 酒店  */
        max_money   = 0,
        customer    = null,
        hotelData   = null,
        hotelPrice  = null;

    apiready = function() {
        api.parseTapmode();
        //机票
        if (card_submit_type === 1) {
            plane_msg = api.pageParam.plane_msg; //舱位信息
            planeInfo = api.pageParam.planeInfo;//航班信息
            selected_staff = api.pageParam.selected_staff; //获取出行人信息
            if (isApply === 1) { //开启申请单条件下
                //处理数据，出行人id数组
                travel_people = [];
                for (let i in selected_staff.business_traveler) {
                    travel_people[i] = selected_staff.business_traveler[i].user_id;
                }
                $api.setStorage('travel_people', travel_people.join(','));
            } else { //未开启申请单
                $api.setStorage('travel_people', selected_staff.join(','));
            }
        }
        //火车票
        if (card_submit_type === 0) {
            //火车票传过来的参数
            train_type = api.pageParam.train_type; //获取火车类型
            seat_name = api.pageParam.seat_name; //获取座位名
            selected_staff = $api.getStorage('travel_people_id_array'); //获取出行人信息
        }
        //酒店
        if (card_submit_type === 2) {
            customer   = $api.getStorage('travel_people').split(',').length;
            hotelData  = JSON.parse($api.getStorage('hotel_data'));

            hotelPrice = parseInt(Math.ceil((JSON.parse($api.getStorage('checked_rate_plans')).TotalRate/hotelData.date_amount)));
            //获取是否开启差旅政策汇总
            let param = {};
            param.url = Config.hotel.getIsOpenTc;
            param.data = {};
            ajax(param, function(ret){
                if (ret.code === 1) {
                    // console.log(JSON.stringify(hotelData));
                    hotelData.isOpenTc = ret.data.hotel_travel_collect;
                    $api.setStorage('hotel_data',JSON.stringify(hotelData));
                } else {
                    $toast(ret.msg);
                }
            });
        }
        if (card_submit_type === 0) {
            $api.setStorage('travel_people_spare', $api.getStorage('travel_people_id_array'));
            get_policy_list($api.getStorage('travel_people_id_array'));
        } else {
            $api.setStorage('travel_people_spare', $api.getStorage('travel_people'));
            get_policy_list($api.getStorage('travel_people'));
        }
    };

    //获取出行人列表
    function get_policy_list(ids) {
        if (ids === 'win') {
            ids = $api.getStorage('travel_people_spare');

            $api.setStorage('travel_people_id_array', ids);
            $api.setStorage('travel_people', ids);
        }
        // console.log(ids);
        let param = {};
        if (card_submit_type === 0) {
            param.url = Config.train.getMultiTrainPolicy;
            param.data = {
                seatType: train_type,
                seatName: seat_name,
                userIds: ids
            };
        } else if (card_submit_type === 1) {
            //获取选中的购票人员信息
            let discount = plane_msg.discount; //机票折扣
            //处理日期
            let start_time = $api.getStorage('aircraf_start_time'); //机票起飞日期
            start_time = start_time.substr(0, 4) + '-' + start_time.substr(5, 2) + '-' + start_time.substr(8, 2);
            start_time = Date.parse(start_time);
            let now_time = Date.parse(new Date(new Date().setHours(0, 0, 0, 0)));
            let days = parseInt((start_time - now_time) / (24 * 60 * 60 * 1000));
            // travel_people = $api.getStorage('travel_people');
            param.url = Config.plane.getMultiPlanePolicy;
            param.data = {
                userIds: ids,
                discount: discount,
                days: days
            };
        } else if (card_submit_type === 2) {
            //因公为多人订票
            param.url = Config.hotel.getHotelMultiPolicy;
            param.data = {
                city : api.pageParam.city,
                price : api.pageParam.price,
                userIds : ids
            };
        }
        // console.log(JSON.stringify(param));
        ajax(param, function(data) {
            $('.user_list,.policy_list').empty();
            if (data.code === 1) {
                policyData = data.data;
                // console.log(JSON.stringify(policyData));
                let html = '';
                let policy_html = '';
                let policy_ids = [];
                let person_name = [];
                $(policyData).each(function(key, val) {
                    max_money += val.policyInfo.execResult.money;
                    let policy_id = val.policyInfo.policy_id;
                    html += '<li class="aui-list-item aui-list-item-middle">';
                    html += '<div class="aui-media-list-item-inner">';
                    html += '<div class="aui-list-item-media" >';
                    html += '<i class="iconfont icon-shanchu" onclick="del_user(' + val.user_id + ')"></i>';
                    html += '</div>';
                    html += '<div class="aui-list-item-inner aui-list-item-arrow">';
                    html += '<div class="aui-list-item-text">';
                    html += '<div class="aui-list-item-title aui-font-size-14">' + val.user_name + '</div>';
                    html += '</div>';
                    html += '<div class="aui-list-item-text">' + val.policyInfo.approvalName + '</div>';
                    html += '</div>';
                    html += ' <div class="aui-list-item-right">' + val.policyInfo.policy_name + '</div>';
                    html += '</div></li>';

                    if (person_name.hasOwnProperty(policy_id)) {
                        person_name[policy_id].push(val.user_name);
                    } else {
                        person_name[policy_id] = [];
                        person_name[policy_id].push(val.user_name);
                    }

                    if ($.inArray(policy_id, policy_ids) === -1) {
                        policy_html += '<li class="aui-list-item aui-list-item-middle" onclick="selected_policy(this)">';
                        policy_html += '<div class="policy_execute" style="display: none">' + JSON.stringify(val.policyInfo) + '</div>';
                        policy_html += '<div class="approve_type" style="display: none">' + val.policyInfo.approvalType + '</div>';
                        policy_html += '<div class="aui-media-list-item-inner">';
                        policy_html += '<div class="aui-list-item-inner aui-list-item-arrow">';
                        policy_html += '<div class="aui-list-item-text">';
                        policy_html += '<div class="aui-list-item-title aui-font-size-14">' + val.policyInfo.policy_name + '<span class="person_name">（<em id="' + policy_id + '"></em>）</span></div>';
                        policy_html += '</div></div>';
                        policy_html += '<div class="aui-list-item-right"><i class="iconfont" style="color:#000;font-size: 1.2rem;"></i></div>';
                        policy_html += '</div></li>';

                        policy_ids.push(policy_id);
                    }
                });
                $('.user_list').append(html);
                $('.policy_list').append(policy_html);
                get_person_name(person_name);
            }
        })
    }

    //获取相同差旅政策的用户名
    function get_person_name(person_name) {
        $('.person_name').each(function(i, item) {
            let id = $(this).find('em').attr('id');
            let person = person_name[id];
            $('#' + id).text(person.join(','));
        });
    }

    //点击图片删除所选人员信息
    function del_user(user_id) {
        if (card_submit_type === 0) {
            travel_people = $api.getStorage('travel_people_id_array').split(',');  //eg:2,3
            // console.log(travel_people);
        } else {
            travel_people = $api.getStorage('travel_people').split(','); //eg:["2","3"]
            // console.log(JSON.stringify(travel_people));
        }
        if (travel_people.length === 1) {
            $toast('不能全部删除出行人');
            return false;
        }
        travel_people.splice($.inArray(user_id.toString(), travel_people), 1);
        $api.setStorage('travel_people', travel_people.join(','));
        //add by hongwei 2018-08-02 因为人员传参乱，重写 /start
        $api.setStorage('travel_people_id_array', travel_people.join(','));
        //add by hongwei 2018-08-02 因为人员传参乱，重写 /end
        get_policy_list(travel_people.join(','));
    }

    //点击选中差旅政策
    function selected_policy(obj) {
        //清楚所有选中的
        $('i').removeClass('icon-duihao');
        $(obj).find('.iconfont').addClass('icon-duihao');
        //获取选中的差旅政策
        policy_execute = $(obj).find('.policy_execute').text();
        let selected_policy = JSON.parse(policy_execute);
        let is_violation = selected_policy.execResult['is_violation'];
        let policy_id = selected_policy.policy_id;

        $api.setStorage('is_violation', is_violation);
        if (card_submit_type === 2) {
            //获取选中的差旅政策
            // console.log($api.jsonToStr(selected_policy));
            let policy = $api.strToJson($api.getStorage("trip_policy"));
            // console.log($api.jsonToStr(policy));
            //差旅政策是否违规内容
            policy.check_msg = selected_policy.execResult['check_msg'];
            //差旅政策详情
            policy.policy_details = selected_policy.policyStr['hotel'];
            //差旅政策名称
            policy.policy_name = selected_policy.policy_name;
            //差旅政策id
            policy.policy_id    = selected_policy.policy_id;
            //是否允许违规预定 1 允许 0 不允许
            policy.is_allow_violation_book = selected_policy.allowance_rule;
            $api.setStorage("trip_policy",JSON.stringify(policy));
            hotelData.policy_max_money = max_money;
            $api.setStorage("hotel_data",JSON.stringify(hotelData));
        } else if (card_submit_type === 1) {
            let selected_policy = JSON.parse(policy_execute);
            $api.setStorage('policy_execute', policy_execute);
            $api.setStorage('check_msg',selected_policy.execResult['check_msg']);
            if (selected_policy.is_violation) {
              $api.setStorage("trip_policy",0);
            } else {
              $api.setStorage("trip_policy",1);
            }
            // $api.setStorage("trip_policy",JSON.stringify(policy));
            $api.setStorage('policy_id', policy_id);
        } else if (card_submit_type === 0) {
            $api.setStorage('policy_execute', policy_execute);
            $api.setStorage('policy_id', policy_id);
        }
    }

    //确定选项差旅政策
    function confirm_policy() {
        //判断是否有选中的差旅政策
        if (!$('i').hasClass('icon-duihao')) {
            $toast('请先选择差旅政策');
            return false;
        }
        //对违规情况的处理
        let is_violation = $api.getStorage('is_violation');
        //判断是否开启差旅合计
        // console.log(JSON.stringify(hotelData));
        if (card_submit_type === 2 && hotelData.isOpenTc === 1) {
            let roomNum = customer/2;
            roomNum = Math.ceil(roomNum);
            let selected_policy = JSON.parse(policy_execute);
            if(max_money < (hotelPrice * roomNum)) {
                if(!selected_policy.allowance_rule){
                    $alert('当前差旅政策不允许违规预定!');
                    return false;
                } else {
                    is_violation = 'true';
                }
            } else {
                is_violation = 'false';
            }
            $api.setStorage('is_violation', is_violation);
        } else {
            if (is_violation === 'true') {
                //验证选中的差旅政策是否允许违规预定
                if (typeof(policy_execute) !== 'object') {
                  policy_execute = $.parseJSON(policy_execute);
                }
                if (card_submit_type === 1) {
                    policyData = policy_execute.policyStr.flight;
                } else if(card_submit_type === 0){
                    policyData = policy_execute.policyStr.train;
                } else if(card_submit_type === 2) {
                    policyData = policy_execute.policyStr.hotel;
                }
                if (policyData.indexOf('不允许违规预定') !== -1) {
                    $alert('当前差旅政策不允许违规预定');
                    return false;
                }
            }
        }
        //跳转处理
        if (card_submit_type === 1) {
            //打开机票提交页面
            api.openWin({
                name: 'plane_order_win',
                url: '../aircraft/plane_order_win.html',
                pageParam: {
                    planeInfo : planeInfo,
                    plane_msg : plane_msg,
                    selected_staff : $api.getStorage('travel_people'),
                    slidBackEnabled:false
                }
            });
        } else if(card_submit_type === 0){
            //打开火车票提交页面
            api.openWin({
                name: 'submit_order',
                url: '../train/submit_order_win.html',
                slidBackEnabled:false
            });
        } else if(card_submit_type === 2) {
            //打开酒店提交页面
            api.openWin({
                name: 'submit_order_win',
                url: '../hotel/submit_order_frm.html',
                slidBackEnabled:false
            });

        }
    }

</script>

</html>
